﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using StateGrid;
using StateGrid.User;


class CatalogHierarchyItem
{
    public Catalog Content;
    public int Level;
    public CatalogHierarchyItem Parent;
    public List<CatalogHierarchyItem> Childs;

    public CatalogHierarchyItem(Catalog catalog, CatalogHierarchyItem parent)
    {
        Content = catalog;
        Parent = parent;
        Childs = new List<CatalogHierarchyItem>();
    }
}

public class CatalogAttribute
{
}

public abstract partial class IndexBasePage : StateGrid.CommonPage
{
    // 在子类中实现以下方法
    protected abstract void DoInit();                           // 初始化时调用
    protected abstract List<Catalog> GetCatalogs();             // 获得分类表
    protected abstract string GetListItemPageURL();             // 展示用URL
    protected abstract string GetAddCatalogPageURL();           // 添加分类的页面链接
    protected abstract bool IsLeafCatalog(string catalog);      // 该类别下是否还有子类别

    // 子类可以调用的方法

    // master控件
    private Panel catalogHierarchyPanel = null;
    private Panel catalogListPanel = null;
    private TextBox searchTextBox = null;
    private Button searchButton = null;
    private HtmlGenericControl displayFrame = null;

    private Dictionary<string, CatalogHierarchyItem> catalogMap = new Dictionary<string,CatalogHierarchyItem>();
    private CatalogHierarchyItem rootCatalog = null;
    private CatalogHierarchyItem currentCatalog = null;
    private string keyword = "";

    protected void Page_Load(Object sender, EventArgs e)
    {
        if (!IsLogIn())
        {
            return;
        }

        DoInit();
        
        InitControls();

        ReloadData();

        RefreshContent();
    }

    /// <summary>
    /// 判断用户是否登录
    /// </summary>
    private bool IsLogIn()
    {
        bool flag = true;
        if (!UserManageDAO.IsLogin((User)Session["login"]))
        {
            GlobalMethod.RedirectLogin(Response);
            flag = false;
        } 
        return flag;
    }

    private void InitControls()
    {
        catalogHierarchyPanel = Master.FindControl("catalogHierarchyPanel") as Panel;
        catalogListPanel = Master.FindControl("catalogListPanel") as Panel;
        searchTextBox = Master.FindControl("searchTextBox") as TextBox;
        searchButton = Master.FindControl("searchButton") as Button;
        displayFrame = Master.FindControl("displayFrame") as HtmlGenericControl;

        searchButton.Click += new EventHandler(SearchButton_Click);
    }

    private void ReloadData()
    {
        ParseCatalogHierarchy();

        currentCatalog = ParseQuery("catalog", s => catalogMap[s], rootCatalog);
    }

    private void RefreshContent()
    {
        RefreshHierarchyPanel();
        RefreshChildPanel();

        if (!IsPostBack)
        {
            RefreshFrame(BuildFrameURL(currentCatalog.Content.Code, keyword)) ;
        }
    }

    private void RefreshHierarchyPanel()
    {
        LinkedList<Catalog> catalogs = new LinkedList<Catalog>();
        CatalogHierarchyItem temp = currentCatalog;
        while (temp != null)
        {
            catalogs.AddFirst(temp.Content);
            temp = temp.Parent;
        }

        foreach (Catalog catalog in catalogs)
        {
            Button button = MakeCatalogButton(catalog);
            catalogHierarchyPanel.Controls.Add(button);
        }
    }

    private void RefreshChildPanel()
    {
        foreach (CatalogHierarchyItem item in currentCatalog.Childs)
        {
            Button button = MakeCatalogButton(item.Content);
            button.Width = Unit.Percentage(100);
            catalogListPanel.Controls.Add(button);
        }

        if (!IsLeafCatalog(currentCatalog.Content.Code))
        {
            Button addButton = new Button();
            addButton.Text = "添加分类";
            addButton.Width = Unit.Percentage(100);
            addButton.Font.Size = FontUnit.Large;
            addButton.Click += new EventHandler(AddButton_Click);
            catalogListPanel.Controls.Add(addButton);
        }

    }

    private void RefreshFrame(string url)
    {
        displayFrame.Attributes.Add("src", url);
    }

    private Button MakeCatalogButton(Catalog catalog)
    {
        Button button = new Button();
        if (catalog.Name.Length > 6)
        {
            button.Text = catalog.Name.Substring(0, 6);
        }
        else
        {
            button.Text = catalog.Name;
        }
        button.ToolTip = catalog.Name;
        button.ID = catalog.Code;
        button.Font.Size = FontUnit.Large;
        button.Click += new EventHandler(CatalogButton_Click);

        return button;
    }

    private string BuildIndexURL(string catalog)
    {
        // 根据原始url构造新查询参数
        return BuildURL(Request.RawUrl,
                        "catalog", catalog);
    }

    private string BuildFrameURL(string catalog, string keyword)
    {
        return BuildURL(GetListItemPageURL(),
                        "catalog", catalog,
                        "keyword", keyword);
    }

    private string BuildCatalogURL(string catalog)
    {
        return BuildURL(GetAddCatalogPageURL(),
                        "parent", catalog);
    }

    private void CatalogButton_Click(Object sender, EventArgs e)
    {
        Response.Redirect(BuildIndexURL((sender as Button).ID));
    }

    private void SearchButton_Click(Object sender, EventArgs e)
    {
        keyword = searchTextBox.Text.Trim();
        
        RefreshFrame(BuildFrameURL(currentCatalog.Content.Code, keyword));
    }

    private void AddButton_Click(Object sender, EventArgs e)
    {
        RefreshFrame(BuildCatalogURL(currentCatalog.Content.Code));
    }

    private void ParseCatalogHierarchy()
    {
        List<Catalog> catalogs = GetCatalogs();

        //添加额外分类
        Catalog exCatalog = new Catalog();
        exCatalog.Code = "";
        exCatalog.Name = "中国成果";

        catalogs.Sort((x, y) => x.Code.Length - y.Code.Length);
        
        rootCatalog = new CatalogHierarchyItem(exCatalog, null);
        catalogMap.Add(rootCatalog.Content.Code, rootCatalog);
        
        List<int> lengthHistory = new List<int>();
        lengthHistory.Add(catalogs[0].Code.Length); 
        
        for (int i = 0; i < catalogs.Count; ++i)
        {
            Catalog catalog = catalogs[i];

            //添加2位的一级编码
            if (catalog.Code.Length == 1)
            {
                CatalogHierarchyItem chItem = new CatalogHierarchyItem(catalog, rootCatalog);
                rootCatalog.Childs.Add(chItem);

                catalogMap.Add(catalog.Code, chItem);
            }
            else //添加后续分类编码
            {
                for (int j = lengthHistory.Count - 1; j >= 0; --j)
                {
                    int length = lengthHistory[j];
                    CatalogHierarchyItem parent;
                    if (catalogMap.TryGetValue(catalog.Code.Substring(0, length), out parent))
                    {
                        CatalogHierarchyItem item = new CatalogHierarchyItem(catalog, parent);
                        parent.Childs.Add(item);

                        catalogMap.Add(catalog.Code, item);
                        break;
                    }
                }
            }

            if (catalog.Code.Length > lengthHistory.Last())
                lengthHistory.Add(catalog.Code.Length);
        }
    }
}